<?php
class SupplierParser{

	public static function Instance(){
		return new SupplierParser();
	}

	public function parseArea($result){
		$result_array = array();
		foreach ($result as $item){
			if (!empty($item['road'])){
				$entity = new Entity();
				$entity->entityName = "Area";
				$entity->entityValue = $item;
				array_push($result_array, $entity);
			}
		}
		$entity = new Entity();
		$entity->entityName = "AreaList";
		$entity->entityValue = $result_array;
		$xml = XmlUtil::Factory()->entityToXml($entity,0,0);
		return $xml;
	}
	

	public function parseSupplierResultToXml($result){
		if ($result instanceof Model_Supplier){
			$entity = $this->parseSupplier($result);
		}else{
			$result_array = array();
			foreach ($result as $item){
				array_push($result_array, $this->parseSupplier($item));
			}
			$entity = new Entity();
			$entity->entityName = "Suppliers";
			$entity->entityValue = $result_array;
		}

		$xml = XmlUtil::Factory()->entityToXml($entity,0,0);
		return $xml;
	}

	private function parseSupplier($item){
		$itemArray['SupplierId'] = $item->id;
		$itemArray['SupplierName'] = $item->name;
		$itemArray['Address'] = $item->address;
		$itemArray['Road'] = $item->road;
		$itemArray['MapAddress'] = $item->map_address;
		$itemArray['Longtitude'] = $item->longitude;
		$itemArray['Latitude'] = $item->latitude;
		$itemArray['Phone'] = $item->phone;
		$itemArray['Phone2'] = $item->phone2;
		$itemArray['TelePhone'] = $item->telephone;
		$itemArray['TelePhone2'] = $item->telephone2;
		$itemArray['JoinTime'] = $item->jointime;
		$itemArray['StartTime'] = $item->starttime;
		$itemArray['EndTime'] = $item->endtime;
		$itemArray['LeastPrice'] = $item->leastprice;
		$itemArray['LeastDistance'] = $item->leastdistance;
		$itemArray['DeliveryDesc'] = $item->deliverydesc;
		$itemArray['AvgPrice'] = $item->avgprice;
		$itemArray['ConsumeRecord'] = $item->consumerecord;
		if (!empty($item->picture)){
			if (file_exists(realpath($this->defaultImgPath().$item->picture))){
				$itemArray['ImgUrl'] = URL::domain().SUP_IMG_PATH.$item->picture;
			}else{
				$itemArray['ImgUrl'] = "";
			}
		}else{
			$itemArray['ImgUrl'] = "";
		}
		$itemArray['Desc'] = $item->desc;
		$itemArray['SupplierCategoryId'] = $item->sup_cate_id;
		$itemArray['CityId'] = $item->city;
		$itemArray['ModifyTime'] = $item->modifytime;
		$itemArray['SupplierCategoryName'] = ORM::factory("supplierCategory", $item->sup_cate_id)->name;
		$itemArray['DishCount'] = ORM::factory("dish")->where("supplierid","=",$item->id)->and_where("status","=","A")->count_all();
		$itemArray['Distance'] = $item->distance;
		$entity = new Entity();
		$entity->entityName = "Supplier";
		$entity->entityValue = $itemArray;
		return $entity;
	}
	
	private function defaultImgPath(){
		return $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.Upload::$default_directory.DIRECTORY_SEPARATOR.'supplier'.DIRECTORY_SEPARATOR;
	}
}